package com.example.baimao_tp.data.repository

import android.util.Log
import com.example.baimao_tp.data.ReferenceImage
import com.example.baimao_tp.data.model.MediaItem
import com.example.baimao_tp.data.model.MediaResponse
import com.example.baimao_tp.network.RetrofitClient
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow

class ReferenceImageRepository {
    private val TAG = "ReferenceImageRepo"
    private val apiService = RetrofitClient.apiService

    init {
        Log.d(TAG, "ReferenceImageRepository初始化完成")
    }

    suspend fun getReferenceImages(language: String = "en"): Result<List<ReferenceImage>> {
        Log.d(TAG, "开始获取参考图片数据，语言: $language...")

        return try {
            Log.d(TAG, "调用API: getMediaList()")
            val response = apiService.getMediaList()

            Log.d(TAG, "API响应成功 - code: ${response.code}, msg: ${response.msg}")

            // 添加空安全检查
            if (response.data?.list == null) {
                Log.e(TAG, "API响应数据为空: data.list is null")
                return Result.failure(Exception("服务器响应数据格式异常"))
            }

            Log.d(TAG, "原始数据总数: ${response.data.list.size}")

            if (response.code == 0) {
                // 过滤数据
                val filteredItems = response.data.list.filter { it.type == "image" && it.status == "active" }
                Log.d(TAG, "过滤后的图片数量: ${filteredItems.size}")

                // 转换数据，传入语言参数
                val referenceImages = filteredItems.mapIndexed { index, item ->
                    Log.d(TAG, "转换第${index + 1}个图片项: id=${item.id}, filename=${item.filename}, url=${item.url}, 语言=$language")
                    val referenceImage = item.toReferenceImage("https://baimao-hz.cn", language) // 传入语言参数
                    Log.d(TAG, "转换结果 - id=${referenceImage.id}, imageUrl=${referenceImage.imageUrl}, description=${referenceImage.description}")
                    referenceImage
                }

                Log.d(TAG, "数据转换完成，返回${referenceImages.size}个参考图片")
                Result.success(referenceImages)
            } else {
                Log.e(TAG, "API返回错误 - code: ${response.code}, msg: ${response.msg}")
                Result.failure(Exception(response.msg))
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取参考图片数据失败", e)

            // 提供更友好的错误信息
            val errorMessage = when {
                e is java.net.ConnectException -> {
                    "无法连接到服务器，请检查服务器是否运行在 ${RetrofitClient.getBaseUrl()}"
                }
                e is java.net.SocketTimeoutException -> {
                    "网络请求超时，请检查网络连接"
                }
                e is java.net.UnknownHostException -> {
                    "无法解析服务器地址，请检查网络连接"
                }
                e.message?.contains("Unable to resolve host") == true -> {
                    "无法连接到服务器，请检查服务器地址和网络连接"
                }
                else -> {
                    "网络请求失败: ${e.message ?: "未知错误"}"
                }
            }

            Result.failure(Exception(errorMessage))
        }
    }

    // Flow版本用于实时更新
    fun getReferenceImagesFlow(language: String = "en"): Flow<Result<List<ReferenceImage>>> = flow {
        try {
            val response = apiService.getMediaList()
            if (response.code == 0) {
                // 添加空安全检查
                if (response.data?.list == null) {
                    emit(Result.failure(Exception("服务器响应数据格式异常")))
                    return@flow
                }

                val referenceImages = response.data.list
                    .filter { it.type == "image" && it.status == "active" }
                    .map { it.toReferenceImage("https://baimao-hz.cn", language) } // 传入语言参数
                emit(Result.success(referenceImages))
            } else {
                emit(Result.failure(Exception(response.msg)))
            }
        } catch (e: Exception) {
            emit(Result.failure(e))
        }
    }

    // 使用tags参数获取参考图片
    suspend fun getReferenceImagesWithTags(language: String = "en", tags: String): Result<List<ReferenceImage>> {
        Log.d(TAG, "开始获取带tags的参考图片数据，语言: $language, tags: $tags")

        return try {
            Log.d(TAG, "调用API: getMediaListWithTags(tags=$tags)")
            val response = apiService.getMediaListWithTags(tags = tags)

            Log.d(TAG, "带tags的API响应成功 - code: ${response.code}, msg: ${response.msg}")

            // 添加空安全检查
            if (response.data?.list == null) {
                Log.e(TAG, "API响应数据为空: data.list is null")
                return Result.failure(Exception("服务器响应数据格式异常"))
            }

            Log.d(TAG, "带tags的原始数据总数: ${response.data.list.size}")

            if (response.code == 0) {
                // 过滤数据
                val filteredItems = response.data.list.filter { it.type == "image" && it.status == "active" }
                Log.d(TAG, "过滤后的图片数量: ${filteredItems.size}")

                // 转换数据，传入语言参数
                val referenceImages = filteredItems.mapIndexed { index, item ->
                    Log.d(TAG, "转换第${index + 1}个图片项: id=${item.id}, filename=${item.filename}, url=${item.url}, 语言=$language, tags=$tags")
                    val referenceImage = item.toReferenceImage("https://baimao-hz.cn", language)
                    Log.d(TAG, "转换结果 - id=${referenceImage.id}, imageUrl=${referenceImage.imageUrl}, description=${referenceImage.description}")
                    referenceImage
                }

                Log.d(TAG, "带tags的数据转换完成，返回${referenceImages.size}个参考图片")
                Result.success(referenceImages)
            } else {
                Log.e(TAG, "带tags的API返回错误 - code: ${response.code}, msg: ${response.msg}")
                Result.failure(Exception(response.msg))
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取带tags的参考图片数据失败", e)

            val errorMessage = when {
                e is java.net.ConnectException -> {
                    "无法连接到服务器，请检查服务器是否运行在 ${RetrofitClient.getBaseUrl()}"
                }
                e is java.net.SocketTimeoutException -> {
                    "网络请求超时，请检查网络连接"
                }
                e is java.net.UnknownHostException -> {
                    "无法解析服务器地址，请检查网络连接"
                }
                e.message?.contains("Unable to resolve host") == true -> {
                    "无法连接到服务器，请检查服务器地址和网络连接"
                }
                else -> {
                    "网络请求失败: ${e.message ?: "未知错误"}"
                }
            }

            Result.failure(Exception(errorMessage))
        }
    }
}

// 如果需要Result的loading状态，可以创建自己的Result类
sealed class NetworkResult<out T> {
    data class Success<out T>(val data: T) : NetworkResult<T>()
    data class Error(val exception: Throwable) : NetworkResult<Nothing>()
    object Loading : NetworkResult<Nothing>()
}